if (!String.prototype.padStart) {
    String.prototype.padStart = function padStart(targetLength, padString) {
        targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
        padString = String(typeof padString !== 'undefined' ? padString : ' ');
        if (this.length > targetLength) {
            return String(this);
        } else {
            targetLength = targetLength - this.length;
            if (targetLength > padString.length) {
                padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
            }
            return padString.slice(0, targetLength) + String(this);
        }
    };
}

/**
 * 手机端展示
 */
;!function(win) {
    "use strict";
    var miniChat = function() {

        },
        WS,
        audio = {
            index: [9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            num: 17,
            timer: null,
            audioobj: null,
            recorder: null,
            mp3Blob: null,
            btnStart: null,
            btnStop: null,
            audio_layer: null
        },
        config = {
            WS: '',
            ykinfo: {
                from_id: '',
                from_group: '',
                from_nick: '',
                from_avatar: '',
            },
            kfinfo: {
                to_id: '',
                to_group: '',
                to_nick: '',
                to_avatar: ''
            }
        }, getaudio = function() {
            audio.audio_layer = layer.open({
                type: 1,
                title: '',
                skin: 'layui-layer-audio',
                closeBtn: 0,
                anim: 2,
                shadeClose: true,
                content: '<button class="btn btn-round btn-default" id="btnStart" disabled>录制</button><button class="btn btn-round btn-default" id="btnStop" disabled>发送</button>',
                end: function () {
                    clearInterval(audio.timer);
                }
            });
            audio.audioobj = $('.layui-m-layer-layui-layer-audio');
            audio.btnStart = $('#btnStart');
            audio.btnStop  = $('#btnStop');
            setTimer();
            audio.recorder = new MP3Recorder({
                debug: true,
                funOk: function () {
                    audio.btnStart.attr('disabled', false);
                },
                funCancel: function (msg) {
                    audio.recorder = null;
                }
            });
        } ,setTimer = function() {
            audio.timer = setInterval(function () {
                setTimeout(function () {
                    audio.num++;
                    audio.audioobj.css("background", "url('/static/common/images/ic_record@2x.png') no-repeat 28px 16px/64px 104px, url('/static/common/images/ic_record_ripple@2x-" + audio.index[audio.num] + ".png') no-repeat 111.2px 32px/28.8px 88px rgba(0, 0, 0, .7)");
                }, 70);
                if (audio.num >= audio.index.length - 1) {
                    audio.num = 0;
                }
            }, 70);
        }, funStart = function(button) {
            audio.btnStart.attr('disabled', true);
            audio.btnStop.attr('disabled', false);
            audio.recorder.start();
        }, funStop = function(button) {
            audio.recorder.stop();
            audio.btnStart.attr('disabled', false);
            audio.btnStop.attr('disabled', true);
            audio.recorder.getMp3Blob(function (blob) {
                audio.mp3Blob = blob;
                funUpload();
            });
        }, funUpload = function() {
            var formData = new FormData();
            var layer_load = null;
            audio.mp3Blob = new File([audio.mp3Blob], encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3'));
            formData.append('file', audio.mp3Blob);
            $.ajax({
                url:'/api.php/Upload/ajaxupaudio.html',
                method: 'post',
                data: formData,
                dataType: 'json',
                processData: false,
                contentType: false,
                cache: false,
                async: false,
                beforeSend: function() {
                    layer_load = layer.open({type: 2});
                },
                success: function(res) {
                    if (res.errno == 0) {
                        emptyShowMessage();
                        var text = "<div class='mess-audio'><audio src='"+res.data[0]+"'></audio><i class='iconfont icon-yuyin'></i></div>";
                        // utype=say_to代表客服给游客聊天
                        var message = '{"data":"'+text+'","type":"say-file","utype":"say_from","from_id":"'+config.ykinfo.from_id+'","from_nick":"'+config.ykinfo.from_nick+'","from_avatar":"'+config.ykinfo.from_avatar+'","to_id":"'+config.kfinfo.to_id+'","to_nick":"'+config.kfinfo.to_nick+'","to_avatar":"'+config.kfinfo.to_avatar+'"}';
                        var from_tpl = '<li class="chatmsg">'+
                                '<p class="customerMsgTime">'+getTime()+'</p>'+
                                '<div class="outer-right">'+
                                    '<div class="customer">'+
                                        '<pre class="robot_text_msg">'+text+'</pre>'+
                                    '</div>'+
                                '</div>'+
                                '<div class="user-avatar-right">'+
                                    '<img src="'+config.ykinfo.from_avatar+'" />'+
                                '</div>'+
                            '</li>';
                        $('#chatbox_input').val("");
                        playPrompt();
                        $('#histStart').append(from_tpl);
                        scrollTopfooter();
                        updateConsultingNumber(
                            config.ykinfo.from_id,
                            config.kfinfo.to_id
                        );
                        WS.send(message);
                        layer.close(layer_load);
                        layer.close(audio.audio_layer);
                    }
                }
            });
        }, register = function() {
            var protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
            WS = new ReconnectingWebSocket(protocol + config.WS);
            WS.onopen = function() {
                console.log('握手成功');
                var login_info = '{"type":"youke_login","fromid":'+config.ykinfo.from_id+',"toid":'+config.kfinfo.to_id+',"name":"'+config.ykinfo.from_nick+'","avatar":"'+config.ykinfo.from_avatar+'"}';
                WS.send(login_info);
                //每30秒ping服务器
                setInterval(function() {
                    WS.send('{"type":"ping"}');
                }, 30000);
            };

            WS.onmessage = function(evt) {
                let data = JSON.parse(evt.data);
                // console.log(data);
                switch (data.type) {
                    case 'ping':
                        WS.send(JSON.stringify({
                            type: 'ping',
                            fromid: config.ykinfo.from_id
                        }));
                        break;
                    // 已经被分配了客服
                    case 'connect':
                        // showMessage('客服 ' + data.data.kf_name + ' 为您服务');
                        break;
                    case 'no_online':
                        showMessage('对方不在线，已留言');
                        offlinerecord();//离线记录
                        break;
                    case 'helloMessage':
                        showMessage(data.data.content);
                        break;
                    // case 'kf_online':
                    //     showMessage(data.data.kf_name + '客服上线了');
                    //     break;
                    case 'zj_yk_online':
                        relinkMessage(data.data);
                        showMessage('客服 ' + data.data.kf_nick + ' 为您服务');
                        break;
                    case 'say':
                        if (data.data.utype == 'say_to') {
                            playPrompt();
                            we_im_update_current_left_message(data.data);
                        }
                        break;
                    case 'goods':
                        layer.open({
                            title: false,
                            style: 'position:fixed; bottom:0; left:0; width: 100%; height: 500px; padding:0px 0; border:none;',
                            content: "<iframe id='chatGoodsIframe' src='"+data.data+"'   scrolling='yes'  style='border:none;height:490px;width:100%'></iframe>",
                            success: function(elem){
                                //$("#chatGoodsIframe").contents().find('body').data('mobile',true);
                                $(elem).find('.layui-m-layercont').css('padding','0')
                            }
                        });
                        break;
                }
            };

            WS.onclose = function(e) {

            };

            WS.onerror = function(e) {

            };
        }, event = function() {
            /**
             * 发送表情
             */
            $('#face-btn').click(function(e) {
                e.stopPropagation();
                let faces = "";
                let face_main = $('#face-con');
                if (face_main.find('img').length <= 0) {
                    $.each(faces_lists,function(title, img) {
                        faces += '<li>'+
                            '<span title="smile" class="emoji-face">'+
                                '<img title="'+title+'" src="'+img+'" />'+
                            '</span> '+
                        '</li>';
                    });
                    face_main.find('ul').html(faces);
                }
                face_main.css({
                    'top':'-85px',
                    'height':'85px',
                    'opacity':1
                });
                $('#face-con').toggle();
            });

            /**
             * 点击表情
             */
            $('body').on('click','#face-con ul li img', function() {
                $('#face-con').toggle();
                insertAtCaret($("#chatbox_input"), $(this).attr('title'));
            });

            /**
             * 发送文本信息
             */
            $('#chatmsg_submit').click(function() {
                var falg = '';
                var txt = htmlEncode($.trim($('#chatbox_input').val()));
                var text = txt.replace(/\[.+?\]/g, function(a,b) {
                    falg = ' img';
                    return "<img src='"+faces_lists[a]+"'/>";
                });
                if (!text) return;
                emptyShowMessage();
                // utype=say_from代表游客给客服聊天
                text = " "+text+" ";/*客服消息*/
                var message = '{"data":"'+text+'","type":"say-text","utype":"say_from","from_id":"'+config.ykinfo.from_id+'","from_nick":"'+config.ykinfo.from_nick+'","from_avatar":"'+config.ykinfo.from_avatar+'","to_id":"'+config.kfinfo.to_id+'","to_nick":"'+config.kfinfo.to_nick+'","to_avatar":"'+config.kfinfo.to_avatar+'"}';
                message = message.replace(/\n/g,"<br/>");
                text = text.replace(/\n/g, "<br/>");

                var from_tpl = '<li class="chatmsg">'+
                    '<p class="customerMsgTime">'+getTime()+'</p>'+
                    '<div class="outer-right">'+
                        '<div class="customer">'+
                            '<pre class="robot_text_msg">'+text+'</pre>'+
                        '</div>'+
                    '</div>'+
                    '<div class="user-avatar-right">'+
                        '<img src="'+config.ykinfo.from_avatar+'" />'+
                    '</div>'+
                '</li>';
                $('#chatbox_input').val("");
                playPrompt();
                $('#histStart').append(from_tpl);
                scrollTopfooter();
                updateConsultingNumber(
                    config.ykinfo.from_id,
                    config.kfinfo.to_id
                );
                WS.send(message);
                hook('user_send', message, false);
                hook('goods_check', message, false);
            });

            /**
             * 上传图片
             */
            $("#image-btn").change(function() {
                var formData = new FormData();
                formData.append('ajaxupimg', $('#upload_img').get(0).files[0]);
                formData.append('user_id', config.ykinfo.from_id);
                formData.append('field', 'ajaxupimg');
                formData.append('user_type', 2);
                $('#upload_img').val('');
                $.ajax({
                    url:'/api.php/Upload/ajaxupimg.html',
                    method: 'post',
                    data: formData,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    cache: false,
                    async: false,
                    success: function(res) {
                        if (res.errno == 0) {
                            emptyShowMessage();
                            var text = "<div class='mess-img'><img src='"+res.data[0]+"' /></div>";
                            // utype=say_to代表客服给游客聊天
                            var message = '{"data":"'+text+'","type":"say-img","utype":"say_from","from_id":"'+config.ykinfo.from_id+'","from_nick":"'+config.ykinfo.from_nick+'","from_avatar":"'+config.ykinfo.from_avatar+'","to_id":"'+config.kfinfo.to_id+'","to_nick":"'+config.kfinfo.to_nick+'","to_avatar":"'+config.kfinfo.to_avatar+'"}';
                            var from_tpl = '<li class="chatmsg">'+
                                '<p class="customerMsgTime">'+getTime()+'</p>'+
                                '<div class="outer-right">'+
                                    '<div class="customer">'+
                                        '<pre class="robot_text_msg">'+text+'</pre>'+
                                    '</div>'+
                                '</div>'+
                                '<div class="user-avatar-right">'+
                                    '<img src="'+config.ykinfo.from_avatar+'" />'+
                                '</div>'+
                            '</li>';
                            $('#chatbox_input').val("");
                            playPrompt();
                            $('#histStart').append(from_tpl);
                            scrollTopfooter();
                            updateConsultingNumber(
                                config.ykinfo.from_id,
                                config.kfinfo.to_id
                            );
                            WS.send(message);
                        }
                    }
                });
            });

            /**
             * 上传文件
             */
            $("#file-btn").change(function() {
                var formData = new FormData();
                formData.append('ajaxupfile', $('#upload_file').get(0).files[0]);
                formData.append('user_id', config.ykinfo.from_id);
                formData.append('field', 'ajaxupfile');
                formData.append('user_type', 2);
                $('#upload_file').val('');
                $.ajax({
                    url:'/api.php/Upload/ajaxupfile.html',
                    method: 'post',
                    data: formData,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    cache: false,
                    async: false,
                    success: function(res) {
                        if (res.errno == 0) {
                            emptyShowMessage();
                            var text = "<div class='mess-file'><a href='"+res.data[0]+"' target='_blank'>查看文件</a></div>";
                            // utype=say_to代表客服给游客聊天
                            var message = '{"data":"'+text+'","type":"say-file","utype":"say_from","from_id":"'+config.ykinfo.from_id+'","from_nick":"'+config.ykinfo.from_nick+'","from_avatar":"'+config.ykinfo.from_avatar+'","to_id":"'+config.kfinfo.to_id+'","to_nick":"'+config.kfinfo.to_nick+'","to_avatar":"'+config.kfinfo.to_avatar+'"}';
                            var from_tpl = '<li class="chatmsg">'+
                                '<p class="customerMsgTime">'+getTime()+'</p>'+
                                '<div class="outer-right">'+
                                    '<div class="customer">'+
                                        '<pre class="robot_text_msg">'+text+'</pre>'+
                                    '</div>'+
                                '</div>'+
                                '<div class="user-avatar-right">'+
                                    '<img src="'+config.ykinfo.from_avatar+'" />'+
                                '</div>'+
                            '</li>';
                            $('#chatbox_input').val("");
                            playPrompt();
                            $('#histStart').append(from_tpl);
                            scrollTopfooter();
                            updateConsultingNumber(
                                config.ykinfo.from_id,
                                config.kfinfo.to_id
                            );
                            WS.send(message);
                        }
                    },
                    error: function () {
                        layer.open({
                            content: '不允许上传该文件'
                            ,skin: 'msg'
                            ,time: 2
                        });
                    }
                });
            });

            /**
             * 评价显示
             */
            $('.msg-toolbar .appraise-btn').click(function() {
                $.post('/chat/say/evaluation.html', {cuid:config.kfinfo.to_id}, function (r) {
                    if (r.code == 200) {
                        layer.open({
                            title: ['您对我还满意吗？']
                            ,content: '<div class="satisfactionBox">'+r.data+'</div>'
                            ,btn: ['提交', '取消']
                            ,yes: function(index) {
                                var data = [];
                                $.each($('.satisfactionBox .evaluate-score'),function(index, item) {
                                    data.push({
                                        score: $(this).attr('data-score'),
                                        sname: $(this).find('input').attr('name')
                                    });
                                });
                                $.post('/chat/say/addevaluation.html', {
                                    ykid:config.ykinfo.from_id,
                                    kfid:config.kfinfo.to_id,
                                    data:data,
                                    stext:$('.about-text').val()
                                }, function (r2) {
                                    layer.open({
                                        content: r2.data
                                        ,skin: 'msg'
                                        ,time: 2
                                    });
                                    if (r2.code == 200) {
                                        setTimeout(function() {
                                            layer.close(index);
                                            $('#appraise-btn').hide();
                                        },2000);
                                    }
                                });
                            }
                        });
                    }
                });
            });

            /**
             * 点击评分
             */
            $('body').on('click', '.star',function(row) {
                let light = '/images/star/star-1.png';
                let dark = '/images/star/star-3.png';
                let star = '/images/star/star-2.png';
                let index = row.target.dataset.id;
                $(this).parent().find('.star').attr('src',star);
                switch(index) {
                    case '1':
                        $(this).attr('src',dark);
                        $(this).parent('.evaluate-item').attr('data-score',1)
                        break;
                    case '2':
                        $(this).attr('src',dark);
                        $(this).prev('.star').attr('src',dark)
                        $(this).parent('.evaluate-item').attr('data-score',2)
                        break;
                    case '3':
                        $(this).attr('src',light);
                        $(this).prevAll('.star').attr('src',light);
                        $(this).parent('.evaluate-item').attr('data-score',3)
                        break;
                    case '4':
                        $(this).attr('src',light);
                        $(this).prevAll('.star').attr('src',light)
                        $(this).parent('.evaluate-item').attr('data-score',4)
                        break;
                    case '5':
                        $(this).parent().find('.star').attr('src',light);
                        $(this).parent('.evaluate-item').attr('data-score',5)
                        break;
                }
            });

            /**
             * 聊天记录中的语音播放
             */
            $('body').on('click', '.chatmsg .mess-audio', function() {
                playAudio($(this));
            });

            /**
             * 语音界面显示
             */
            $('body').on('click', '#audio-btn', function() {
                getaudio();
            });

            /**
             * 录制
             */
            $('body').on('click','#btnStart', function() {
                funStart($(this));
            });

            /**
             * 发送
             */
            $('body').on('click','#btnStop', function() {
                funStop($(this));
            });

            /**
             * 加载更多
             */
            $('.showtime #show-more').click(function() {
                loadMessageHistory('top');
            });

            /**
             * 点击常见问题
             */
            $('.recommend_ul .recommend_li').click(function() {
                var obj = $(this);
                $.post('/api.php/Record/getComaskContent.html', {id:obj.attr('data-id')}, function (r) {
                    if (r.code == 200) {
                        var from_tpl = '<li class="chatmsg">'+
                            '<p class="customerMsgTime">'+getTime()+'</p>'+
                            '<div class="outer-right">'+
                                '<div class="customer">'+
                                    '<pre class="robot_text_msg">' + obj.text() + '</pre>'+
                                '</div>'+
                            '</div>'+
                            '<div class="user-avatar-right">'+
                                '<img src="' + config.ykinfo.from_avatar + '" />'+
                            '</div>'+
                        '</li>'+
                        '<li class="chatmsg out deal">'+
                            '<div class="user-avatar-left">'+
                            '<img src="' + config.kfinfo.to_avatar + '" />'+
                            '</div>'+
                            '<p class="service-name">' + config.kfinfo.to_nick + '<span class="agentMsgTime">'+getTime()+'</span></p>'+
                            '<div class="outer-left">'+
                                '<div class="service">'+
                                    '<pre class="robot_text_msg">' + r.data + '</pre>'+
                                '</div>'+
                            '</div>'+
                        '</li>';
                        $('#histStart').append(from_tpl);
                        emptyShowMessage();
                        scrollTopfooter();
                    }
                });
            });

            if (!isMobile()) {
                $('#showinfo').css('display', 'block');
                $('.msg-toolbar-footer span').css('margin', '0 30px 0 0');
            }

            /**
             * 显示发送快捷键
             */
            $('#showinfo').click(function () {
                var shortcuts = Cookies.get('admin-shortcuts');
                if (!shortcuts) {
                    Cookies.get('admin-shortcuts', 2);
                    shortcuts = 2;
                }
                $('#fuceng').toggle();
                if (shortcuts == 1) {
                    $('#type1').addClass('selected-li');
                    $('#type2').removeClass('selected-li');
                } else {
                    $('#type2').addClass('selected-li');
                    $(' #type1').removeClass('selected-li');
                }
            });

            $(document).keypress(function (e) {
                var shortcuts = Cookies.get('admin-shortcuts');
                if ((e.which == 13 && e.ctrlKey) || (e.which == 10 && e.ctrlKey) && !isMobile()) {
                    var content = $.trim($('#chatbox_input').val());
                    $("#chatbox_input").val(content + "\n");
                    if (shortcuts == 2) {
                        $('#chatmsg_submit').click();
                    }
                } else if (e.which == 13 && !isMobile()) {
                    if (shortcuts == 1) {
                        $('#chatmsg_submit').click();
                    }
                }
            });

            /**
             * 点击发送快捷键
             */
            $('#fuceng ul li').click(function () {
                Cookies.set('admin-shortcuts', $(this).attr('type'));
                $(this).addClass('selected-li').siblings().removeClass('selected-li');
            });

        }, isMobile = function () {
            if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
                return true;
            } else {
                return false;
            }
        }, emptyShowMessage = function () {
            // 清空客服提示信息
            $('#histStart .msg').addClass('none');
        }, playAudio = function(mess) {
            var media = mess.find('audio')[0];
            media_play(media);
            mess.find('i').addClass('weight');
            media.onended = function () {
                mess.find('i').removeClass('weight');
            };
            // var media = mess.find('audio')[0];
            // if(media.paused) {
            //     media_play(media);
            //     mess.find('i').addClass('weight');
            // } else {
            //     media_pause(media);
            //     mess.find('i').removeClass('weight');
            // }
            // media.onended = function () {
            //     mess.find('i').removeClass('weight');
            // };
        }, media_pause = function(media) {
            media.pause();
        }, media_play = function(media) {
            media.play();
        }, scrollTopfooter = function () {
            // 到底部
            setTimeout(function() {
                $('#wrap').scrollTop($("#wrap")[0].scrollHeight);
            },100);
        }, updateConsultingNumber = function (ykid,kfid) {
            // 更新咨询次数
            $.post('/api.php/Record/updateConsultingNumber.html', {ykid:ykid,kfid:kfid},function () {});
        }, playPrompt = function () {
            if ($('#new-chat').length > 0) {
                $('#new-chat')[0].play();
            }
        }, getTime = function () {
            var today = new Date();
            var hours = today.getHours() < 10 ? '0'+today.getHours() : today.getHours();
            var mins = today.getMinutes() < 10 ? '0'+today.getMinutes() : today.getMinutes();
            var secs = today.getSeconds() < 10 ? '0'+today.getSeconds() : today.getSeconds();
            return hours + ":" + mins + ":" + secs;
        },getLocalTime = function(time_stamp) {
            const time = new Date(time_stamp * 1000);
            const h = time.getHours().toString().padStart(2, '0')
            const m = time.getMinutes().toString().padStart(2, '0')
            const s = time.getSeconds().toString().padStart(2, '0')
            return h+':'+m+':'+s;
        }, showMessage = function(content) {
            var unreadLine = $('#histStart');
            unreadLine.append('<li class="showtime msg">'+content+'</li>');
        }, loadMessageHistory = function(direction ) {
            var hist = $('#histStart');
            var load_page = parseInt(hist.attr('page'));
            var more = $('#show-more').parent();
            if (hist.attr('sw') == 'off') {
                more.html('没有消息了');
                return;
            }

            $.ajax({
                type: "post",
                url: '/api.php/Record/loadMessageHistory.html',
                data: {
                    fromid:config.ykinfo.from_id,
                    toid:config.kfinfo.to_id,
                    page: load_page
                },
                dataType: "json",
                success: function (r) {
                    if (r.code == 200) {
                        var message = "";
                        more.removeClass('none');
                        $.each(r.data, function (index, item) {
                            if (item.utype == 'say_to') {
                                message += '<li class="chatmsg out deal">'+
                                    '<div class="user-avatar-left">'+
                                        '<img src="' + item.send_avatar + '" />'+
                                    '</div>'+
                                    '<p class="service-name">' + item.send_nick + '<span class="agentMsgTime">'+getLocalTime(item.send_time)+'</span></p>'+
                                    '<div class="outer-left">'+
                                        '<div class="service">'+
                                            '<pre class="robot_text_msg">' + item.content + '</pre>'+
                                        '</div>'+
                                    '</div>'+
                                '</li>';
                            } else {
                                message += '<li class="chatmsg">'+
                                    '<p class="customerMsgTime">'+getLocalTime(item.send_time)+'</p>'+
                                    '<div class="outer-right">'+
                                        '<div class="customer">'+
                                            '<pre class="robot_text_msg">' + item.content + '</pre>'+
                                        '</div>'+
                                    '</div>'+
                                    '<div class="user-avatar-right">'+
                                        '<img src="' + item.send_avatar + '" />'+
                                    '</div>'+
                                '</li>';
                            }
                        });
                        if (direction == 'bottom') {
                            $('#histStart').append(message);
                            scrollTopfooter();
                        } else {
                            more.after(message);
                        }
                        load_page++;
                        hist.attr('page', load_page);
                        if (r.data.length < 10) {
                            hist.attr('sw', 'off');
                        } else {
                            hist.attr('sw', 'on');
                        }

                    } else {
                        hist.attr('sw', 'off');
                    }
                }
            });
        },we_im_update_current_left_message = function(data) {
            var from_tpl = '<li class="chatmsg out deal">'+
                '<div class="user-avatar-left">'+
                    '<img src="' + data.send_avatar + '" />'+
                '</div>'+
                '<p class="service-name">' + data.send_nick + '<span class="agentMsgTime">'+getLocalTime(data.send_time)+'</span></p>'+
                '<div class="outer-left">'+
                    '<div class="service">'+
                        '<pre class="robot_text_msg">' + data.content + '</pre>'+
                    '</div>'+
                '</div>'+
            '</li>';
            $('#histStart').append(from_tpl);
            scrollTopfooter();
        }, relinkMessage = function(data) {
            $.post('/api.php/Record/saychaturl.html', {code:window.location.href,cuid:data.kf_id}, function (r) {
                if (r.code == 200) {
                    loadMessageHistory('bottom');
                    $('#ser-company').text('和'+data.name+'客服聊天中');
                    window.history.pushState(null, null, r.url);
                    config.kfinfo.to_id = data.kf_id;
                    config.kfinfo.to_nick = data.kf_nick;
                    config.kfinfo.to_avatar = data.kf_avatar;
                }
            });
        };

    miniChat.prototype.init = function(options) {
        options.WS = options.WS,
            options.ykinfo = options.ykinfo,
            options.kfinfo  = options.kfinfo,
            config = options;
        register();
        event();
        loadMessageHistory('bottom');
    }
    win.miniChat = new miniChat();

} (window);

function insertAtCaret(obj, myValue) {
    var $t = obj[0];
    if (document.selection) {
        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
    } else if ($t.selectionStart || $t.selectionStart == '0') {
        var startPos = $t.selectionStart;
        var endPos = $t.selectionEnd;
        var scrollTop = $t.scrollTop;
        $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
        this.focus();
        $t.selectionStart = startPos + myValue.length;
        $t.selectionEnd = startPos + myValue.length;
        $t.scrollTop = scrollTop;
    } else {
        this.value += myValue;
        this.focus();
    }
}

function hook(event, params, once) {
    console.log('mobile:hook');
    var formData = new FormData();
    formData.append('event', event);
    formData.append('params', params);
    formData.append('once', once);
    var result = null;
    $.ajax({
        url: IM_config.hook,
        method: 'post',
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        cache: false,
        async: false,
        success: function (res) {
            console.log(res);
            result = res;
            return res;
        }
    });
    return result;
}

function htmlEncode(value){
    return $('<div/>').text(value).html();
}


/**
 * 离线弹窗
 */
function offlinerecord() {
    var check = hook('offlinerecordcheck', null, 1);
    console.log(check);
    if (check.status == 'success'){
        /**
         * 打开留言弹窗
         */
        var openIndex = layer.open({
            shade:0.3,
            closeBtn:0,
            title: false,
            scrollbar:false,
            content:"<iframe id='leaveMsgIframe' src=" + check.message + "   scrolling='yes'  style='border:none;height:450px;width:100%'></iframe>",
            btn: ['确认留言', '关闭']
            ,yes: function(index, layero){
                $("#leaveMsgIframe").contents().find('.submit-button').click();
            }
            ,btn2: function(index, layero){
                layer.close(index);
            },
            style: 'position:fixed; bottom:0; left:0; width: 100%; height: 500px; padding:0px 0; border:none;',
            success: function(elem){
                $("#leaveMsgIframe").contents().find('body').data('mobile',true);
                $(elem).find('.layui-m-layercont').css('padding','0')
            }
        });
    }
}

/**
 * 会员消费
 */
$("#user_pay").on('click', function () {

    var openIndex = layer.open({
        type: 2,
        title: '会员消费',
        skin: 'layui-layer-rim-record',
        area: ['300px', '400px'],
        content: IM_config.user_pay,
        btn: ['确认', '取消',],
        cancel: function (index, layero) {
            $(layero).find('a.layui-layer-close').prop('target', '_self');
        },
        yes: function (index, layero) {

            var to_id = youke_info.from_id;
            var to_nick = youke_info.from_nick;
            var to_avatar = youke_info.from_avatar;
            var from_id = kefu_info.to_id;
            var from_nick = kefu_info.to_nick;
            var from_avatar = kefu_info.to_avatar;

            var childframe = layer.getChildFrame('body', openIndex);
            var account = $(childframe).find('#account').val();
            var user = $(childframe).find('#user').val();
            var lists = $(childframe).find('#lists').val();
            var type = $(childframe).find('#type').val();
            var send = $(childframe).find('input[name="send"]:checked').val();
            var pay_type = $(childframe).find('input[name="pay_type"]:checked').val();
            if (!to_id) {
                layer.msg('请刷新重试')
                return false;
            }
            if (!lists) {
                layer.msg('请选择购买内容')
                return false;
            }

            var index = layer.load();
            var params = {
                to_id: to_id,
                to_nick: to_nick,
                to_avatar: to_avatar,
                from_id: from_id,
                from_nick: from_nick,
                from_avatar: from_avatar,
                id: lists,
                send: send,
                type: type,
                pay_type: pay_type,
                account: account,
                user: user,
            };
            console.log('params:', params);
            var result = hook('user_pay', JSON.stringify(params), 1);
            layer.close(index);
            if (result == false || result.status != 'success') return false;

            layer.close(openIndex);
        },
    });
});

